package com.softtek.ibeacon.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Hashtable;
import java.util.Properties;

import javax.naming.AuthenticationException;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import com.softtek.ibeacon.service.config.ConfigurationsProxyImpl;

public class LdapAround {

 

	protected final String PROP_FILE_PATH = ConfigurationsProxyImpl.INSTANCE
			.getAgsSeamConfDir()
			+ ".security.".replace('.', File.separatorChar);
	protected final String PROP_FILE_NAME = "ldapconfig.properties";

	protected final String INITIAL_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";

	/**
	 * @throws LiteEJBException
	 * @throws IOException
	 * 
	 * @param name
	 * @param password
	 * @param remoteAddr
	 *            ServletContexts.instance().getRequest().getRemoteAddr()
	 * @return
	 * @throws
	 */
	public void checkAuthenticationFromAD(String name, String password,
			String fromIp) throws Exception {
		Hashtable<String, String> env = new Hashtable<String, String>(11);
		try {
			loadProperties(env, fromIp);
		} catch (IOException ioe) {
			throw new Exception("Loading AD Configuration Error...");
		}

		// Check authentication
		env.put(Context.SECURITY_PRINCIPAL, name);
		env.put(Context.SECURITY_CREDENTIALS, password);
		try {
			DirContext ctx = null;
			ctx = new InitialDirContext(env);
		} catch (AuthenticationException authe) {
			System.out.println("Invalid User / Password.");
 
		} catch (CommunicationException ce) {
			System.out.println("Can not connect AD Server.");
		} catch (NamingException e) {
			System.out.println("Connect AD Server error.");
 
		} finally {
			// try {
			// ctx.close();
			// } catch (Exception e) {
			// logger.warn("AD server disconnect error...");
			// }
		}
	}

	private void loadProperties(Hashtable<String, String> env, String fromIp)
			throws IOException {
 

		// Load properties file.
		Properties ldPorp = new Properties();
		FileInputStream fileInputStream = new FileInputStream(new File(
				PROP_FILE_PATH + File.separatorChar + PROP_FILE_NAME));
		ldPorp.load(fileInputStream);
		fileInputStream.close();

		// Loading valuse to hashtable
		env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
		env.put(Context.SECURITY_AUTHENTICATION, ldPorp
				.getProperty("SECURITY_AUTHENTICATION"));
		env.put(Context.REFERRAL, "follow");

		if (isExternalDomain(ldPorp.getProperty("EXTERNAL_CHECK_IP"), fromIp)) {
			env.put(Context.PROVIDER_URL, ldPorp
					.getProperty("EXTERNAL_PROVIDER_URL"));
			env.put(Context.SECURITY_PRINCIPAL, ldPorp
					.getProperty("EXTERNAL_SECURITY_PRINCIPAL"));
			env.put(Context.SECURITY_CREDENTIALS, ldPorp
					.getProperty("EXTERNAL_SECURITY_CREDENTIALS"));
		} else {
			env.put(Context.PROVIDER_URL, ldPorp
					.getProperty("DOMAIN_PROVIDER_URL"));
			env.put(Context.SECURITY_PRINCIPAL, ldPorp
					.getProperty("SECURITY_PRINCIPAL"));
			env.put(Context.SECURITY_CREDENTIALS, ldPorp
					.getProperty("SECURITY_CREDENTIALS"));
		}
	}

	private boolean isExternalDomain(String _EXTERNAL_CHECK_IP, String fromIp) {
//		logger.debug("getRemoteAddr() of checkExternalDomain==>" + fromIp);
		if (fromIp.substring(0, _EXTERNAL_CHECK_IP.length()).equals(
				_EXTERNAL_CHECK_IP)) {
//			logger
//					.debug("checkExternalDomain of LdapServiceImpl is External AD!!");
			return true;
		} else {
//			logger
//					.debug("checkExternalDomain of LdapServiceImpl is Internal AD!!");
			return false;
		}
	}

	public static void main(String[] args) throws UnknownHostException,
			NamingException, IOException {
		System.out.println("10.36.234.223");

		LdapAround ldapAround = new LdapAround();
//		ldapAround.checkAuthenticationFromAD("Steve.sun@AD", "password",
//				"10.36.4.218");
	}

}
